# coding=utf-8

from collections import OrderedDict
from docx import Document
from pprint import pprint
import time
import json
import re


# def word2json(word_path: str, json_path: str):
async def word2json(word_path: str):
    # async def word2json(document: Document):

    '''
    :param word_path: word 路径
    :return: index_paragraph_sentence_dict = {升序索引：{文本:str, 段落索引列表: []}}
    '''

    t1 = time.time()
    document = Document(word_path)

    index_contract_dict = OrderedDict()
    # directory_index = float('inf')  # 设置为无限大
    directory_index = 0  # 设置为空
    for index, paragraph in enumerate(document.paragraphs):  # 获取目录后的索引段落字典 index_contract_dict = {段落索引:段落}
        if not paragraph.text.strip():
            continue
        # if '第一节' in re.sub(' ', '', paragraph.text) and '....' not in re.sub(' ', '', paragraph.text):
        if '第一节' in re.sub(' ', '', paragraph.text) and re.sub(' ', '', paragraph.text)[-1] not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
            directory_index = index
            break

    # 修改正则表达式以匹配汉字
    pattern = r"第[一二三四五六七八九十]+节声明"
    statement_index = len(document.paragraphs) + 1
    for index, paragraph in enumerate(document.paragraphs):  # 获取目录后的索引段落字典 index_contract_dict = {段落索引:段落}
        matches = re.findall(pattern, re.sub(' ', '', paragraph.text.strip()[:10]))  # 匹配某个paragraph的前10个字符
        if not paragraph.text.strip():
            continue
        if '第' == re.sub(' ', '', paragraph.text.strip())[0] and len(matches) > 0 and re.sub(' ', '', paragraph.text)[-1] not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
            statement_index = index
            break

    for index, paragraph in enumerate(document.paragraphs):
        if index == statement_index - 1:
            break
        # 获取目录后的索引段落字典 index_contract_dict = {段落索引:段落}
        if not paragraph.text.strip() or paragraph.text.strip()[:4] == '1-1-':
            continue
        if index >= directory_index:
            print(index, paragraph.text)
            # print('=========================================')
            index_contract_dict[int(index)] = paragraph.text.strip()

    print('转word时间：', time.time() - t1)

    index_paragraph_sentence_list = []  # 获取 index_paragraph_sentence_list = [{'文本': '目前，林紫柏作为特邀台商代表列席齐齐哈尔市政协委员会会议。\n', '段落索引列表': [293]}]
    Text = {'文本': '', '段落索引列表': []}
    for dict_index, (paragraph_index, contract) in enumerate(
            index_contract_dict.items()):  # 按[。！!？?]切分 句子(同段落不换行,跨段落换行)
        text = contract.strip()
        # text = contract
        pattern = r'[。！!？?]'
        # 使用re.split()函数切割字符串
        split_text = re.split(pattern, text)
        findall_text = re.findall(pattern, text)
        if split_text[-1] == '':
            split_text = split_text[:-1]
        for i in range(0, len(findall_text)):
            split_text[i] = split_text[i] + findall_text[i]
        # print(f'+++++++++++++++++++++{paragraph_index}+++++++++++++++++++++++++')
        # print(*split_text, sep='\n--------------------\n')
        for text_index, text in enumerate(split_text):
            if text_index == len(split_text) - 1:
                if text[-1] not in ['。', '！', '!', '？', '?']:
                    Text['文本'] += text + '\n'
                    Text['段落索引列表'].append(paragraph_index)
                    ####################################################
                    # index_paragraph_sentence_list.append(Text)
                    # Text = {'文本': '', '段落索引列表': []}
                    ####################################################
                else:
                    Text['文本'] += text + '\n'
                    Text['段落索引列表'].append(paragraph_index)
                    # Text['文本'] = Text['文本'].strip()
                    index_paragraph_sentence_list.append(Text)
                    Text = {'文本': '', '段落索引列表': []}
            else:
                Text['文本'] += text
                Text['段落索引列表'].append(paragraph_index)
                # Text['文本'] = Text['文本'].strip()
                index_paragraph_sentence_list.append(Text)
                Text = {'文本': '', '段落索引列表': []}

        if dict_index == len(index_contract_dict) - 1 and Text['文本'] != '':
            index_paragraph_sentence_list.append(Text)
            Text = {'文本': '', '段落索引列表': []}

    # print(*index_paragraph_sentence_list, sep='\n*****************************************\n')
    index_paragraph_sentence_dict = OrderedDict()  # 获取 index_paragraph_sentence_dict = {0:{文本:'',段落索引列表: []}, 1:{文本:'',段落索引列表: []}}
    for sentence_index in range(1, len(index_paragraph_sentence_list) - 1):
        key = index_paragraph_sentence_list[sentence_index]['文本']
        key_index_list = sorted(index_paragraph_sentence_list[sentence_index]['段落索引列表'])
        if '\n' in index_paragraph_sentence_list[sentence_index - 1]['文本'].strip() and '\n' in index_paragraph_sentence_list[sentence_index + 1]['文本'].strip():  # 有换行符在上一句和下一句中，只能等于自己
            value = index_paragraph_sentence_list[sentence_index]['文本']
            value_index_list = sorted(index_paragraph_sentence_list[sentence_index]['段落索引列表'])
        elif '\n' in index_paragraph_sentence_list[sentence_index - 1]['文本'].strip():  # 有换行符在上一句中，只能+下一句
            if '\n' == index_paragraph_sentence_list[sentence_index]['文本'][-1]:  # 自己是段落结尾，只能所以只能等于自己
                value = index_paragraph_sentence_list[sentence_index]['文本']
                value_index_list = sorted(index_paragraph_sentence_list[sentence_index]['段落索引列表'])
            else:
                value = index_paragraph_sentence_list[sentence_index]['文本'] + index_paragraph_sentence_list[sentence_index + 1]['文本']
                value_index_list = sorted(index_paragraph_sentence_list[sentence_index]['段落索引列表'] + index_paragraph_sentence_list[sentence_index + 1]['段落索引列表'])
        elif '\n' in index_paragraph_sentence_list[sentence_index + 1]['文本'].strip():  # 有换行符在下一句中，只能+上一句
            if '\n' == index_paragraph_sentence_list[sentence_index - 1]['文本'][-1]:  # 上一句是段落结尾，只能所以只能等于自己
                value = index_paragraph_sentence_list[sentence_index]['文本']
                value_index_list = sorted(index_paragraph_sentence_list[sentence_index]['段落索引列表'])
            else:
                value = index_paragraph_sentence_list[sentence_index - 1]['文本'] + index_paragraph_sentence_list[sentence_index]['文本']
                value_index_list = sorted(index_paragraph_sentence_list[sentence_index - 1]['段落索引列表'] + index_paragraph_sentence_list[sentence_index]['段落索引列表'])
        else:
            if '\n' == index_paragraph_sentence_list[sentence_index]['文本'][-1] and '\n' == index_paragraph_sentence_list[sentence_index - 1]['文本'][-1]:  # 自己和上一句都是段落结尾
                value = index_paragraph_sentence_list[sentence_index]['文本']
                value_index_list = sorted(index_paragraph_sentence_list[sentence_index]['段落索引列表'])
            elif '\n' == index_paragraph_sentence_list[sentence_index]['文本'][-1]:  # 自己是段落结尾，只能+上一句
                value = index_paragraph_sentence_list[sentence_index - 1]['文本'] + index_paragraph_sentence_list[sentence_index]['文本']
                value_index_list = sorted(index_paragraph_sentence_list[sentence_index - 1]['段落索引列表'] + index_paragraph_sentence_list[sentence_index]['段落索引列表'])
            elif '\n' == index_paragraph_sentence_list[sentence_index - 1]['文本'][-1]:  # 上一句是段落结尾，只能+下一句
                value = index_paragraph_sentence_list[sentence_index]['文本'] + index_paragraph_sentence_list[sentence_index + 1]['文本']
                value_index_list = sorted(index_paragraph_sentence_list[sentence_index]['段落索引列表'] + index_paragraph_sentence_list[sentence_index + 1]['段落索引列表'])
            else:
                value = index_paragraph_sentence_list[sentence_index - 1]['文本'] + index_paragraph_sentence_list[sentence_index]['文本'] + index_paragraph_sentence_list[sentence_index + 1]['文本']
                value_index_list = sorted(index_paragraph_sentence_list[sentence_index - 1]['段落索引列表'] + index_paragraph_sentence_list[sentence_index]['段落索引列表'] + index_paragraph_sentence_list[sentence_index + 1]['段落索引列表'])

        index_paragraph_sentence_dict[sentence_index] = {}
        index_paragraph_sentence_dict[sentence_index]['文本'] = key
        index_paragraph_sentence_dict[sentence_index]['文本段落索引列表'] = key_index_list
        index_paragraph_sentence_dict[sentence_index]['切片'] = value
        index_paragraph_sentence_dict[sentence_index]['切片段落索引列表'] = value_index_list


    # 加第0句切片
    if '\n' in index_paragraph_sentence_list[1]['文本'].strip():
        key = index_paragraph_sentence_list[0]['文本']
        key_index_list = sorted(index_paragraph_sentence_list[0]['段落索引列表'])
        value = index_paragraph_sentence_list[0]['文本']
        value_index_list = sorted(index_paragraph_sentence_list[0]['段落索引列表'])
    else:
        key = index_paragraph_sentence_list[0]['文本']
        key_index_list = sorted(index_paragraph_sentence_list[0]['段落索引列表'])
        value = index_paragraph_sentence_list[0]['文本'] + index_paragraph_sentence_list[1]['文本']
        value_index_list = sorted(index_paragraph_sentence_list[0]['段落索引列表'] + index_paragraph_sentence_list[1]['段落索引列表'])

    index_paragraph_sentence_dict[0] = {}
    index_paragraph_sentence_dict[0]['文本'] = key
    index_paragraph_sentence_dict[0]['文本段落索引列表'] = key_index_list
    index_paragraph_sentence_dict[0]['切片'] = value
    index_paragraph_sentence_dict[0]['切片段落索引列表'] = value_index_list

    # 加第最后一句切片
    if '\n' in index_paragraph_sentence_list[len(index_paragraph_sentence_list) - 2]['文本'].strip():
        key = index_paragraph_sentence_list[len(index_paragraph_sentence_list) - 1]['文本']
        key_index_list = sorted(index_paragraph_sentence_list[len(index_paragraph_sentence_list) - 1]['段落索引列表'])
        value = index_paragraph_sentence_list[len(index_paragraph_sentence_list) - 1]['文本']
        value_index_list = sorted(index_paragraph_sentence_list[len(index_paragraph_sentence_list) - 1]['段落索引列表'])
    else:
        key = index_paragraph_sentence_list[len(index_paragraph_sentence_list) - 1]['文本']
        key_index_list = sorted(index_paragraph_sentence_list[len(index_paragraph_sentence_list) - 1]['段落索引列表'])
        value = index_paragraph_sentence_list[len(index_paragraph_sentence_list) - 2]['文本'] + index_paragraph_sentence_list[len(index_paragraph_sentence_list) - 1]['文本']
        value_index_list = sorted(index_paragraph_sentence_list[len(index_paragraph_sentence_list) - 2]['段落索引列表'] + index_paragraph_sentence_list[len(index_paragraph_sentence_list) - 1]['段落索引列表'])

    index_paragraph_sentence_dict[len(index_paragraph_sentence_list) - 1] = {}
    index_paragraph_sentence_dict[len(index_paragraph_sentence_list) - 1]['文本'] = key
    index_paragraph_sentence_dict[len(index_paragraph_sentence_list) - 1]['文本段落索引列表'] = key_index_list
    index_paragraph_sentence_dict[len(index_paragraph_sentence_list) - 1]['切片'] = value
    index_paragraph_sentence_dict[len(index_paragraph_sentence_list) - 1]['切片段落索引列表'] = value_index_list

    test_dict = json.dumps(index_paragraph_sentence_dict, indent=4, ensure_ascii=False)

    return index_paragraph_sentence_dict


if __name__ == '__main__':
    import asyncio
    # word_path = '../data/1-1+招股说明书（申报稿）1016(1).docx'
    # word_path = '../data/晶晨半导体（上海）股份有限公司招股书 申报稿.docx'
    # word_path = '../sentence_docx/v1``ac8f6b8c-e1aa-4ba7-80bf-599188c03296`2025`0106.docx'
    # word_path = '../sentence_docx/v1``81ea585a-f195-4940-9ddb-e8a3168f0701`2025`0106.docx'
    # word_path = '../sentence_docx/v1``45044153-120c-45ee-881a-36c835701823`2025`0109.docx'
    # word_path = 'C:\西交\凌志\招股书_报错\docx浙江众鑫环保科技集团股份有限公司主板首次公开发行股票招股说明书（申报稿）.docx'
    # word_path = '../sentence_docx/docx浙江众鑫环保科技集团股份有限公司.docx'
    # word_path = 'C:\西交\凌志\招股书_报错\傲拓科技股份有限公司科创板首次公开发行股票招股说明书（申报稿）.docx'
    # word_path = '../sentence_docx/傲拓科技股份有限公司.docx'
    # word_path = '../sentence_docx/java傲拓科技股份有限公司科创板首次公开发行股票招股说明书.docx'
    word_path = 'C:\西交\凌志\招股书_报错\wps傲拓科技股份有限公司科创板首次公开发行股票招股说明书（申报稿）.docx'
    word_path = 'C:\西交\凌志\招股书_报错\java傲拓科技股份有限公司科创板首次公开发行股票招股说明书（申报稿）.docx'




    index_paragraph_sentence_dict = asyncio.run(word2json(word_path))
    # pprint(index_paragraph_sentence_dict)